#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  Copyright (C) 2008 Wilson Pinto Júnior <wilson@openlanhouse.org>
#  Copyright (C) 2008  Thomaz de Oliveira dos Reis
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import subprocess
import os,sys

def error_window( stderr):
    html="""
    <html>
	<head>
	    <title>Execution Error</title>
	</head>
	<body>
	    <h1>Script Execution Error</h1>
	    <hr>
	    It was not possible to run the specified command.<br/>
	    <br/>
	    <i>Tips:</i><br/>
	    <br/>
	    <li>Verify if you mistyped the script name. </li>
	    <li>If you were trying to open a script in the actual folder, try to add a \"./\" before the script name. </li>
	    <li>Verify if you have enough permissions to run the script (chmod +x might help)</li>
	    <li>Verify if you have the interpreter line in the first line of the script. 
		<br>
		<p style=\"margin-left: 16\"><b>Example:</b></p>
		    <p style=\"margin-left: 32\"> #!/bin/bash <br/>
		    <i> the rest of your script</i></li></p>
	    <hr>
	    <b>Error message:</b><br/>
	    <font color=red>""" + stderr + """</font><br/><hr><i>The ScriptTool dev team </i>
	</body>
    </html>
    """
    
    return html

def execute_command(cmd, env=None):
    """
        Execute command
    """
    if not isinstance(cmd, list):
        cmd = [cmd]
    
    if not env:
        env = os.environ
    
    (stdout, stderr, retval) = ("","",1)
    
    try:
	po = subprocess.Popen(cmd, stdin=None, stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE, env=env)
	retval = po.wait()
	(stdout, stderr) = po.communicate()
    
    except OSError, inst:
	stderr=inst.args[1]
	stdout=error_window(stderr)
    
    return (stdout, stderr, retval)

def execute_command_run(cmd, env=None):
    """
        Execute command
    """
    if not isinstance(cmd, list):
        cmd = [cmd]
    
    if not env:
        env = os.environ
    
    (stdout, stderr, retval) = ("","",1)
    
    try:
	po = subprocess.Popen(cmd)

    
    except OSError, inst:
	stderr=inst.args[1]
	stdout=error_window(stderr)
    
    return (stdout, stderr, retval)

